package com.github.defense.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: lettger
 * @Date: 2021/12/13 下午3:37
 */
public class GsonUtils {

    private static final GsonUtils INSTANCE = new GsonUtils();

    private static final Gson GSON = new GsonBuilder().create();


    public static Gson getGson(){
        return GsonUtils.GSON;
    }

    public static GsonUtils getInstance(){
        return INSTANCE;
    }

    /**
     * 对象转json
     * @param object
     * @return
     */
    public String toJson(final Object object) {
        return GSON.toJson(object);
    }

    /**
     * json 转指定对象
     * @param json
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T fromJson(final String json, final Class<T> tClass) {
        return GSON.fromJson(json, tClass);
    }

    public <T> T fromJson(final JsonElement jsonElement, final Class<T> tClass) {
        return GSON.fromJson(jsonElement, tClass);
    }

    public <T> List<T> fromList(final String json, final Class<T> clazz) {
        return GSON.fromJson(json, TypeToken.getParameterized(List.class, clazz).getType());
    }

    public <T> List<T> fromCurrentList(final String json, final Class<T> clazz) {
        return GSON.fromJson(json, TypeToken.getParameterized(CopyOnWriteArrayList.class, clazz).getType());
    }

    public <T> Map<String, T> toObjectMap(final String json, final Class<T> clazz) {
        return GSON.fromJson(json, TypeToken.getParameterized(Map.class, String.class, clazz).getType());
    }

}
